#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# @file: entry/website/views.py
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Contributors:
#   Dawei Yang   <davy.pristina@gmail.com>
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This file is released under BSD 2-clause license.

from flask import render_template, url_for, redirect, flash
from flask.ext.babel import lazy_gettext, gettext as _

from .context import app
from .forms import SignupForm
from .models import LdapUser, User
from .navibar import navigates, NaviItem


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/signup/', methods=['GET', 'POST'])
def signup():
    form = SignupForm()
    if (form.validate_on_submit()):
        # Construct user data object
        user = User()
        form.populate_obj(user)
        user.set_password(form.password.data)
        # Check whether username or password conflicts
        has_error = False
        if LdapUser.query_by_uid(user.name):
            form.name.errors.append(_('Username already taken'))
            has_error = True
        if LdapUser.query_by_mail(user.email):
            form.email.errors.append(_('Email already taken'))
            has_error = True
        if LdapUser.query_by_student_id(user.student_id):
            form.student_id.errors.append(_('Student ID already taken. Please contact support.'))
            has_error = True
        # Add user if no error
        if (not has_error):
            try:
                LdapUser.sign_up(user)
                flash(_("Account created successfully. Start exploration now!"), 'success')
                return redirect(url_for('index'))
            except Exception:
                app.logger.exception('Cannot create account %s' % user.name)
            flash(_("I'm sorry but we may have met some trouble. "
                    "Please try again."), 'danger')
    return render_template('signup.html', form=form)

# Register all pages into navibar
navigates.add_view(title=lazy_gettext('Home'), endpoint='index')
navigates.add(NaviItem(title=lazy_gettext('Railgun'), url="http://railgun.secoder.net", identity='railgun'))
navigates.add(NaviItem(title=lazy_gettext('JIRA'), url="http://jira.secoder.net", identity='jira'))
navigates.add(NaviItem(title=lazy_gettext('Stash'), url="http://stash.secoder.net", identity='stash'))
navigates.add(NaviItem(title=lazy_gettext('Fisheye+Crucible'), url="http://fisheye.secoder.net", identity='fisheye'))
